package com.yoomiito.app.present.goods;

import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.yoomiito.app.Constant;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.AppConfig;
import com.yoomiito.app.base.BaseActPresenter;
import com.yoomiito.app.model.bean.AppInterfaceInfo;
import com.yoomiito.app.model.bean.GoodsDetail;
import com.yoomiito.app.model.my.YouMI;
import com.yoomiito.app.model.order.ShopCarList;
import com.yoomiito.app.model.sdd.ShareMsg;
import com.yoomiito.app.net.YmApi;
import com.yoomiito.app.ui.goods.NewGoodsInfoActivity;
import com.yoomiito.app.utils.NetworkUtils;
import com.yoomiito.app.utils.YMToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.BaseModel;
import cn.droidlover.xdroidmvp.net.XApi;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class NewGoodsInfoPresenter extends BaseActPresenter<NewGoodsInfoActivity> {

    public NewGoodsInfoPresenter(AppConfig appConfig) {
        super(appConfig);
    }

    /**
     * 商品详情
     *
     * @param id
     */
    public void getGoodsInfo(String id, String type) {
        YmApi.getYmService()
                .getGoodsInfo(id, type)
                .compose(getV().bindToLifecycle())
                .compose(XApi.<GoodsDetail>getApiTransformerData())
                .compose(XApi.<GoodsDetail>getScheduler())
                .subscribe(new ApiSubscriber<GoodsDetail>() {
                    @Override
                    public void onSuccess(GoodsDetail detail) {
                        getV().setGoodsInfo(detail);
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
//                        if (300==error.getCode()){//商品下架
                        getV().pullMarket(error.getMsg());
//                        }
                    }
                });
    }


    public void getInterface(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(YmApi.BaseUrl + url)
                .addHeader("Authorization", SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, ""))
                .addHeader("Site","app_mugwort_android")
                .header("Platform", "")
                .build();
        Call call = client.newCall(request);
        XLog.e(YmApi.BaseUrl + url + "===");
        call.enqueue(new Callback() {
            // 2
            @Override
            public void onFailure(Call call, IOException e) {
                //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();


            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                // 3
                try {
                    JSONObject obj = new JSONObject(response.body().string());
                    String data = obj.getString("data");
                    if (obj.getInt("code") == 200) {
                        AppInterfaceInfo appInterfaceInfo = new Gson().fromJson(data, AppInterfaceInfo.class);
                        getV().jumpBuy(appInterfaceInfo);
                    } else {
                        getV().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    YMToast.showText(obj.getString("msg"));
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                    }
                    XLog.e("=======" + response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }

    /**
     * 关联商品
     *
     * @param id
     */
    public void getRelatedGoods(String id) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        YmApi.getYmService()
                .getRelatedGoods(id)
                .compose(getV().bindToLifecycle())
                .compose(XApi.<List<GoodsDetail>>getApiTransformerData())
                .compose(XApi.<List<GoodsDetail>>getScheduler())
                .subscribe(new ApiSubscriber<List<GoodsDetail>>(handleException()) {
                    @Override
                    public void onSuccess(List<GoodsDetail> goodsDetails) {
//                        getV().setRecommendGoods(goodsDetails);
                    }

                    @Override
                    public void onFail(ApiException error) {

                    }
                });
    }

    /**
     * 添加收藏
     *
     * @param id
     */
    public void addCollection(String id) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        YmApi.getYmService()
                .addCollection(id)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerNoData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<BaseModel>(handleException()) {
                    @Override
                    public void onSuccess(BaseModel baseModel) {
                        getV().showToast("收藏成功");
                    }

                    @Override
                    public void onFail(ApiException error) {

                    }
                });
    }

    /**
     * 取消收藏
     *
     * @param id
     */
    public void delCollection(String id) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        YmApi.getYmService()
                .delCollection(id)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerNoData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<BaseModel>(handleException()) {
                    @Override
                    public void onSuccess(BaseModel baseModel) {
                        getV().showToast("已取消收藏");
                    }

                    @Override
                    public void onFail(ApiException error) {

                    }
                });
    }

    //0元购商详
    public void getFreeGoodsInfo(String id, String productId) {
        YmApi.getYmService()
                .getFreeGoodsInfo(id, productId)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<GoodsDetail>(handleException()) {
                    @Override
                    public void onSuccess(GoodsDetail goodsDetail) {
                        getV().setGoodsInfo(goodsDetail);
//                        getV().dismissLoading();
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
//                        if (ApiException.GOODS_OBTAINED==error.getCode()){//商品下架
                        getV().pullMarket("");
//                        }
                    }
                });
    }

    //领取免费商品
    public void buyFreeGoods(String id, String productId) {
        YmApi.getYmServiceNoErrorCode().buyFreeGoods(id, productId)
                .compose(getV().bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(freeGoodsBuyInfoBaseModel -> {
                    getV().dismissLoading();
                    if (freeGoodsBuyInfoBaseModel.getCode() == 200) {
                        getV().buyFreeGoods(freeGoodsBuyInfoBaseModel.data.getSend_url());
                    } else if (freeGoodsBuyInfoBaseModel.getCode() == 5002) {
                        getV().showFreeGoodsCouponDialog(freeGoodsBuyInfoBaseModel.getData());
                    } else {
                        YMToast.showText(freeGoodsBuyInfoBaseModel.msg);
                    }
                });

    }

    public void addShopCar(String productId) {
        YmApi.getYmService()
                .addShopCar(productId, 1)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerNoData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<BaseModel>() {
                    @Override
                    public void onSuccess(BaseModel baseModel) {
                        getV().dismissLoading();
                        getV().showNewFlag(true);
                        YMToast.showText("添加成功", Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                        if (!TextUtils.isEmpty(error.getMsg()))
                            YMToast.showText(error.getMsg());
                    }
                });

    }

    public void getList(int page) {
        YmApi.getYmService()
                .showCarList(page, 10)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<ShopCarList>(handleException()) {
                    @Override
                    public void onSuccess(ShopCarList shopCarList) {
                        if (shopCarList == null || shopCarList.getData() == null || shopCarList.getData().size() == 0) {
                            getV().showNewFlag(false);
                        } else {
                            getV().showNewFlag(true);
                        }
                    }

                    @Override
                    public void onFail(ApiException error) {

                    }
                });
    }

    /**
     * 送多多--获取分享信息
     *
     * @param type
     * @param goodsId
     */
    public void getSddShareMsg(int type, String goodsId) {
        YmApi.getYmService()
                .shareMsg(type, goodsId)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<ShareMsg>() {
                    @Override
                    public void onSuccess(ShareMsg shareMsg) {
                        getV().sddShareMsg(shareMsg);
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                        if (!TextUtils.isEmpty(error.getMsg()))
                            YMToast.showCenterToast(error.getMsg());
                    }
                });
    }

    public void postShareNum(String goodsID) {
        YmApi.getYmService()
                .postShareNum(goodsID)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerNoData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<BaseModel>() {

                    @Override
                    public void onSuccess(BaseModel baseModel) {

                    }

                    @Override
                    public void onFail(ApiException error) {

                    }
                });
    }

}
